package com.lyy.yygh.common.helper;

import io.jsonwebtoken.*;
import org.springframework.util.StringUtils;

import java.util.Date;

public class JwtHelper {
    //token过期时间设置 ms
    private static long tokenExpiration = 24*60*60*1000;
    //签名密钥
    private static String tokenSignKey = "123456";
    //根据字符串生成一个token
    public static String createToken(Long userId, String userName) {
        String token = Jwts.builder()
                .setSubject("YYGH-USER")//设置过期时间
                .setExpiration(new Date(System.currentTimeMillis() + tokenExpiration)) //设置过期时间
                //封装私有部分，用户自定义内容用户id和名字
                .claim("userId", userId)
                .claim("userName", userName)                       
                .signWith(SignatureAlgorithm.HS512, tokenSignKey)    //设置加密方式和加密密码
                .compressWith(CompressionCodecs.GZIP)
                .compact();
        return token;
    }
    //根据token把id还原出来

    public static Long getUserId(String token) {
        if(StringUtils.isEmpty(token)){
            return null;
        }

        Jws<Claims> claimsJws = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        Integer userId = (Integer)claims.get("userId");
        return userId.longValue();
    }

    //根据token把用户名称还原出来
    public static String getUserName(String token) {
        if(StringUtils.isEmpty(token)) {
            return "";
        }
        Jws<Claims> claimsJws
                = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token);
        Claims claims = claimsJws.getBody();
        return (String)claims.get("userName");
    }
    public static void main(String[] args) {
        String token = JwtHelper.createToken(1L, "Lucy");
        System.out.println(token);
        System.out.println(JwtHelper.getUserId(token));
        System.out.println(JwtHelper.getUserName(token));
    }
}
